/**
 * SysController.java 
 * Copyright © 2015-3015, 杭州泊享网络科技有限公司
 * 
 * @author wenlong Hua
 * @create 2015年11月9日
 */
package com.pshare.artemis.nologin;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.support.RequestContextUtils;

import com.pshare.artemis.order.bean.Order;
import com.pshare.artemis.order.enums.OverdueState;
import com.pshare.artemis.order.service.OrderService;
import com.pshare.artemis.parkingdevice.bean.Gateway;
import com.pshare.artemis.parkingdevice.bean.ParkingDevice;
import com.pshare.artemis.parkingdevice.enums.UpDownState;
import com.pshare.base.bean.SeaxResponse;
import com.pshare.constant.SeaxConstants;
import com.pshare.framework.controller.WebController;
import com.pshare.framework.exception.SeaxRuntimeException;
import com.pshare.util.DateUtils;
import com.pshare.util.HttpUtils;
import com.pshare.util.StringUtils;
import com.pshare.util.SysPropertyUtils;

/**
 * 无登录Contrller
 */
@Controller
public class NoLoginController extends WebController{
	
	private static final Logger logger = Logger.getLogger(NoLoginController.class);

	@Autowired
	private OrderService orderService;
	
	/**
	 * 微信预订(网关列表)
	 * @return String
	 */
	@RequestMapping(value = "/nopl/wxgatewaylist", method = RequestMethod.GET)
	public String  gList(ModelMap model) {
		String host=SysPropertyUtils.getProperty("gateway.url");
		Long userId=6108920146855016449L;
		String url=host+"api/getGatewayList/"+userId;
		JSONObject obj=HttpUtils.getJsonInUrlGet(url);
		List<Gateway> list=null;
		if(obj!=null){
			String str=obj.getString("data");
			JSONArray array = JSONArray.fromObject(str);
			list=JSONArray.toList(array, Gateway.class);
		}
		model.addAttribute("list", list);
		return "/nologin/gList" ;
	}
	
	/**
	 * 网关下获取锁（半小时内没有被预订的锁）
	 * @return String
	 */
	@RequestMapping(value = "/nopl/golocklist/{gatewayId}", method = RequestMethod.GET)
	public String  gLockList(@PathVariable Long gatewayId,ModelMap model) {
		List<ParkingDevice> listdata=new ArrayList<ParkingDevice>();
		List<Order> orderList=orderService.getAll();
		String host=SysPropertyUtils.getProperty("gateway.url");
		String url=host+"api/getLockListBygid/"+gatewayId;
		JSONObject obj=HttpUtils.getJsonInUrlGet(url);
		List<ParkingDevice> list=null;
		if(obj!=null){
			String str=obj.getString("data");
			JSONArray array = JSONArray.fromObject(str);
			list=JSONArray.toList(array, ParkingDevice.class);
		}
		
		if(orderList==null||(orderList.size()==0)){
			model.addAttribute("list", list);
		}else{
			for(int i=0;i<orderList.size();i++){
				
				Iterator<ParkingDevice> iter = list.iterator();
				
				while(iter.hasNext()){
					ParkingDevice pd = iter.next();
					int cdate=DateUtils.minutesBetween(orderList.get(i).getStartTime(), new Date());
					if(orderList.get(i).getLockMac().equals(pd.getMac())){
						if(pd.getUpDownState().intValue()==UpDownState.DOWN.getCode()||cdate<=30){
							iter.remove();
						}
						
					}
				}
				
			}
			model.addAttribute("list", list);
		}
		
		
		return "/nologin/gLockList" ;
	}
	
	/**
	 * 微信预订页面
	 * @return String
	 */
	@RequestMapping(value = "/nopl/gowxorder", method = RequestMethod.GET)
	public String  goWXorder(HttpServletRequest request,ModelMap model) {
		String id=request.getParameter("id");
		String name=request.getParameter("name");
		String mac=request.getParameter("mac");
		String gatewayName=request.getParameter("gatewayName");
		ParkingDevice bean=new ParkingDevice();
		bean.setId(Long.valueOf(id));
		bean.setName(name);
		bean.setMac(mac);
		bean.setGatewayName(gatewayName);
		
		model.addAttribute("bean", bean);
		return "/nologin/wxOrder" ;
	}
	
	/**
	 * 微信预订车位 获取coder
	 * @return String
	 */
	@RequestMapping(value = "/nopl/wxorder", method = RequestMethod.GET)
	public String  wxorder(HttpServletRequest request,RedirectAttributes attr) {
		String code=request.getParameter("code");
		String state=request.getParameter("state");
		logger.info("state:"+state);
		if(StringUtils.isEmpty(code)||StringUtils.isEmpty(state)){
			throw new SeaxRuntimeException("code或者 state为空");
		}
		String[] parms=state.split(",");
		String openId="";
		String host=SeaxConstants.WX_TOKEN;
	    String appid=SysPropertyUtils.getProperty("wx.appid");
	    String appsecret=SysPropertyUtils.getProperty("wx.appsecret");
	    
	    String url=host+"?appid="+appid+"&secret="+appsecret+"&code="+code+"&grant_type=authorization_code";
		JSONObject obj=HttpUtils.getJsonInUrlGet(url);
		if(obj!=null){
			 openId=obj.getString("openid");
		}else{
			throw new SeaxRuntimeException("未能获得用户信息");
		}
		logger.info("openId:"+openId+"length:"+parms.length);
		if(parms.length>1){//等于1 是查看记录
			if(orderService.hasNoOverDue(openId)){
				attr.addFlashAttribute(SeaxConstants.PAGE_KEY_ERROR, "您已经预定过车位，不能重复预订");
			}else{
				String mac=parms[1];
				String id=parms[0];
				String name=parms[2];
				String gatewayName=parms[3];
				//保存用户数据
				Order bean= new Order();
				bean.setLockMac(mac);
				bean.setUserOpenId(openId);
				bean.setLockName(name);
				bean.setGatewayName(gatewayName);
				orderService.add(bean);
				attr.addFlashAttribute(SeaxConstants.PAGE_KEY_SUCCESS, SeaxConstants.ORDER_SUCCESS);
				
			}
		}
		
		//attr.addFlashAttribute("openId", openId);
		return SeaxConstants.URL_REDIRECT+ "/nopl/orderlist?openId="+openId;
	}
	
	
	
	/**
	 * 微信预订记录
	 * @return String
	 */
	@RequestMapping(value = "/nopl/orderlist", method = RequestMethod.GET)
	public String  wxorderlist(HttpServletRequest request,ModelMap model,RedirectAttributes attr) {
		
		String openId=request.getParameter("openId");
		String redUrl="/nologin/ovDueOrderList";
		if(StringUtils.isEmpty(openId)){
			String code=request.getParameter("code");
			String host=SeaxConstants.WX_TOKEN;
		    String appid=SysPropertyUtils.getProperty("wx.appid");
		    String appsecret=SysPropertyUtils.getProperty("wx.appsecret");
		    String url=host+"?appid="+appid+"&secret="+appsecret+"&code="+code+"&grant_type=authorization_code";
		    logger.info("+++orderlist+url:"+url);
		    JSONObject obj=HttpUtils.getJsonInUrlGet(url);
			if(obj!=null){
				 openId=obj.getString("openid");
			}else{
				throw new SeaxRuntimeException("未能获得用户信息");
			}
		}
		
		
		
		logger.info("+++openId:"+openId);
		//过期
		List<Order> ovorderList=new ArrayList<Order>();
		//未过期
		List<Order> orderList=new ArrayList<Order>();
		
		List<Order> list=orderService.getByOpenId(openId);
		for(int i=0;i<list.size();i++){
			int cdate=DateUtils.minutesBetween(list.get(i).getStartTime(), new Date());
			if(cdate>30){
				list.get(i).setIsOverdue(OverdueState.YES.getCode());
				ovorderList.add(list.get(i));
			}else{
				list.get(i).setIsOverdue(OverdueState.NO.getCode());
				String host1=SysPropertyUtils.getProperty("gateway.url");
				String url1=host1+"api/getLock/"+list.get(i).getLockMac();
				JSONObject obj1=HttpUtils.getJsonInUrlGet(url1);
				if(obj1.getInt("code")!=200){
					list.get(i).setUpDownState(UpDownState.UP.getCode());
				}else{
					JSONObject jb = new JSONObject().fromObject(obj1.getString("data"));
					ParkingDevice pd = (ParkingDevice)JSONObject.toBean(jb,ParkingDevice.class);
					list.get(i).setUpDownState(pd.getUpDownState());
				}
				orderList.add(list.get(i));
				
			}
		}
		
		if(orderList.size()!=0){
			model.addAttribute("bean", orderList.get(0));
			redUrl="/nologin/orderList";
		}else{
			model.addAttribute("list", ovorderList);
		}
		
		
		return redUrl ;
	}
	
	@ResponseBody
	@RequestMapping(value = "/nopl/updown/{state}/{mac}", method = RequestMethod.POST)
	public SeaxResponse upDown(@Valid @PathVariable String mac,@PathVariable Integer state) {
		String host1=SysPropertyUtils.getProperty("gateway.url");
		String url1=host1+"api/setLock/"+mac+"/"+state;
		JSONObject obj1=HttpUtils.getJsonInUrlGet(url1);
		if(obj1!=null){
			if(obj1.getInt("code")!=200)
				return failed(false,obj1.getString("msg"));
		}else{
			return failed();
		}
		
		
		return succeed();
	}
	
}
